package controllers;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

import models.Attachment;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import play.Logger;
import play.Play;
import play.cache.Cache;
import play.mvc.Controller;

public class Attachments extends Controller {
	
	public static String uploadPath = "/uploads/";

    //GET /attachments/{id}
    public static void show(Long id){
    	
    	Attachment a = null;
    	
    	//缓存
    	Object attachmentCache = Cache.get("Attachment:" + id.toString());
    	if(attachmentCache != null){
    		//System.out.println("hit cache: attachment" + id);
    		a = (Attachment) attachmentCache;
    	} else {
    		//System.out.println("not hit: attachment" + id);
    		a = Attachment.findById(id);
    		notFoundIfNull(a);
    		Cache.add("Attachment:" + id.toString(), a);
    	}
    	
		if(a.filePath != null){
    		renderBinary(Play.getFile(uploadPath + a.filePath));
//    		下面这段有指示contentType
//    		try {
//				renderBinary(new FileInputStream(new File(a.file)), null, a.contentType, false);
//			} catch (FileNotFoundException e) {
//				notFound();
//			}
    	} else if (a.fileContent != null) {
    		renderBinary(new ByteArrayInputStream(a.fileContent));
    	}
    }

    /**
     * POST /attachments
     * 
     * 使用uploadify上传
     */
    public static void create_uploadify(String Filename, File file){
    	
	    UUID randomUUID = UUID.randomUUID();
	    
	    try {

	    	/*保存文件内容*/
			File destFile = Play.getFile(uploadPath + randomUUID.toString());
			FileUtils.copyFile(file, destFile);
			
			/*创建记录*/
			Attachment a = new Attachment();
			a.filePath = randomUUID.toString();
			a.filename = Filename;
			a.save();
			
			/*反馈附件id*/
			renderText(a.id);
			
		} catch (IOException e) {
			Logger.error(e, "上传失败");
			error("上传失败");
		}
    	
    }//create
    
    public static void create_valums(){
    	
    	
    }
    
    /**
     * 把图片设为已被引用状态。
     * @param id
     * @throws Exception 
     */
    public static void activeImage(long id) throws Exception {
    	Attachment a = Attachment.findById(id);
    	if(a == null) throw new Exception("图片("+id+")已经被删除.");
    	a.used = true;
    	a.save();
    }
}
